import sys
import urllib2
import time
import signal
import threading
import Queue
import signal
MAX_QUEUE_SIZE=10
MAX_QUEUE_TIME=10
MAX_ENTRIES_PER_POST=10

#ops syslog insert -> inserts into mongodb
#ops syslog api -> Provides api to interface mongo
#ops syslog tail -> Command line syslog tail
#ops syslog web -> Opens web interface in localhost, connects to same api as 'tail'

class InputReader(threading.Thread):
    def __init__(self,queue):
        threading.Thread.__init__(self)
        self.queue = queue

    def run(self):
        log_entry = {}
        while True:
            line = sys.stdin.readline().strip()
            if line == "end":
                self.queue.put(log_entry)
                log_entry = {}
            elif line.find("=") > -1:
                field,value = line.split("=",1)
                log_entry[field] = value
        
    

class Forwarder():
    def __init__(self,client):
        self.client = client
        self.queue = Queue.Queue()
        self.input_reader = InputReader(self.queue)
        self.input_reader.daemon = True
    
    def start(self):
        last_forward = 0
        self.input_reader.start()    
        while True:
            if self.queue.empty():
                time.sleep(1)
            else:
                if self.queue.qsize() > MAX_QUEUE_SIZE or (time.time() - last_forward) > MAX_QUEUE_TIME:
                    entries = []
                    for i in xrange(0,min(self.queue.qsize(),MAX_ENTRIES_PER_POST)):
                        try:
                            entries.append(self.queue.get_nowait())
                        except Queue.Empty:
                            pass
                    self._forward_entries(entries)
                    last_forward = time.time()
        
    def _forward_entries(self,entries):
        self.client.server_call("syslog",entries)
